const http = require('http')
const fs   = require('fs')
const config = require('./config')
const utils = require('./libs/utils')
const path = require('path')

const server = http.createServer((req, res) => {
    if (req.url === '/favicon.ico') {
        return ;
    }
    const dirname = 'album/aaa/bbb/ccc/ddd'
    // fs.exists(dirname, (exists) => {
    //     if (exists) {
    //         console.log('done')
    //     } else {
    //         fs.mkdir(dirname, {recursive: true}, (err) => {
    //             // if (err) {
    //             //     console.log(err)
    //             // }
    //         })
    //     }
    // })
    mkdirs(dirname, () => {
        console.log('done')
    })
    res.writeHead(200, {'Content-Type': 'text/html;charset=UTF-8'})
    res.end('mkdir成功')
})

// 异步遍历创建文件夹
function mkdirs(dirname, callback) {
    fs.exists(dirname, (exists) => {
        if (exists) {
            callback()
        } else {
            console.log(path.dirname(dirname))
            mkdirs(path.dirname(dirname), () => {
                fs.mkdir(dirname, callback)
                console.log(`在${path.dirname(dirname)}目录创建好${dirname}目录`)
            })
        }
    })
}

server.listen(config.port, config.hostname, () => {
    console.log('listen on port', config.port)
})